<template>
  <div class="homeIndex_box">
    <div v-if="newsData && newsData.length > 0" id="newsHome">
      <transition name="el-fade-in">
        <div class="newsInfo" v-if="newsNum && newsNum > 0">
          <span>有 {{newsNum}} 条新的新闻待查收</span>
          <span @click="findAllDataFirst">&nbsp;&nbsp;刷新&nbsp;&nbsp;</span>
        </div>
      </transition>
      <NewsBar
        v-for="(items,index) in newsData"
        :key="index"
        :tittle="items.text"
        :news-time="items.updated_at"
        :url="items.url"
      />
    </div>
    <Loading v-else />
  </div>
</template>

<script>
import NewsBar from "./NewsBar";
import Loading from "./Loading";
import { findData } from "../newsApi/NewsApi";

export default {
  components: {
    NewsBar,
    Loading
  },
  data() {
    return {
      newsData: undefined,
      newsBegin: 0,
      newsEnd: 0,
      newsNum: 0
    };
  },
  created() {
    this.findAllDataFirst();
    setInterval(this.findNews, 10000);
  },
  beforeDestroy() {
    clearInterval(this.findNews);
  },
  methods: {
    // 数据交互axios
    async findAllDataFirst() {
      this.newsData = await findData("");
      this.newsBegin = Number(this.newsData[0].id.replace(/[^0-9]/gi, ""));
      this.newsEnd = this.newsBegin;
      this.newsNum = this.newsEnd - this.newsBegin;
      if (this.newsData == 0) {
        alert("新闻连接失败");
      }
    },
    async findNews() {
      let data = await findData("");
      this.newsEnd = Number(data[0].id.replace(/[^0-9]/gi, ""));
      this.newsNum = this.newsEnd - this.newsBegin;
      if (this.newsData == 0) {
        alert("新闻连接失败");
      }
    }
  }
};
</script>

<style lang = "less" src = "../newsResource/NewsIndex.less">
</style>
